package com.mazaiting.imqq.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import com.github.promeg.pinyinhelper.Pinyin;
import com.lqr.adapter.LQRAdapterForRecyclerView;
import com.lqr.adapter.LQRViewHolderForRecyclerView;
import com.lqr.recyclerview.LQRRecyclerView;
import com.mazaiting.imqq.R;
import com.mazaiting.imqq.model.bean.Friend;
import com.mazaiting.imqq.model.bean.UserInfo;
import com.mazaiting.imqq.presenter.user.UserManager;
import com.mazaiting.imqq.ui.activity.OtherUserInfoActivity;
import com.mazaiting.imqq.ui.activity.contacts.NewFriendActivity;
import com.mazaiting.imqq.ui.base.BaseFragment;
import com.mazaiting.imqq.ui.view.QuickIndexBar;
import com.mazaiting.imqq.utils.ImageLoaderFactory;
import com.mazaiting.imqq.utils.UIUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 联系人
 * A simple {@link Fragment} subclass.
 */
public class ContactsFragment extends BaseFragment {
  /** 新朋友条目 */
  LinearLayout mLlNewFriend;
  /** 群聊 */
  LinearLayout mLlGroupCheat;
  /** 标签 */
  LinearLayout mLlTag;
  /** 公众号 */
  LinearLayout mLlOfficial;
  /** 新朋友小圆点 */
  View mVNewFriendUnread;
  /** 群聊小圆点 */
  View mVGroupCheatUnread;
  /** 头视图 */
  View mHeaderView;
  /** 尾视图 */
  TextView mFooterView;
  /** 快速插入视图 */
  @BindView(R.id.quickIndexBar_contacts_fragment) QuickIndexBar mQuickIndexBar;
  /** 好友列表视图 */
  @BindView(R.id.rvContacts_contacts_fragment) LQRRecyclerView mRvContacts;
  /** 字母 */
  @BindView(R.id.tvLetter_contacts_fragment) TextView mTvLetter;
  /** 好友列表 */
  private List<Friend> mFriendList = new ArrayList<>();
  /** 好友列表适配器 */
  private LQRAdapterForRecyclerView<Friend> mAdapter;
  /** 设备上下文 */
  private Context mContext;

  @Override public void onAttach(Context context) {
    super.onAttach(context);
    mContext = getActivity();
  }

  public ContactsFragment() {

  }

  /**
   * 初始化头视图与尾视图
   */
  private void initHeaderViewAndFooterView() {
    mHeaderView = View.inflate(mContext, R.layout.header_contacts_rv, null);

    mLlNewFriend = (LinearLayout) mHeaderView.findViewById(R.id.llNewFriend_header_contacts);
    mLlGroupCheat = (LinearLayout) mHeaderView.findViewById(R.id.llGroupCheat_header_contacts);
    mLlTag = (LinearLayout) mHeaderView.findViewById(R.id.llTag_header_contacts);
    mLlOfficial = (LinearLayout) mHeaderView.findViewById(R.id.llOffical_header_contacts);
    mVNewFriendUnread = mHeaderView.findViewById(R.id.vNewFriendUnread_header_contacts);
    mVGroupCheatUnread = mHeaderView.findViewById(R.id.vGroupCheatUnread_header_contacts);

    mFooterView = new TextView(mContext);
    ViewGroup.LayoutParams params =
        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dip2Px(50));
    mFooterView.setLayoutParams(params);
    mFooterView.setGravity(Gravity.CENTER);

    setListener();
  }

  private void setListener() {
    mQuickIndexBar.setListener(new QuickIndexBar.OnLetterUpdateListener() {
      @Override public void onLetterUpdate(String letter) {
        mQuickIndexBar.setBackground(null);
        //显示字母提示
        showLetter(letter);

        //滑动对对应字母条目处
        if ("↑".equalsIgnoreCase(letter)) {
          mRvContacts.moveToPosition(0);
        } else if ("☆".equalsIgnoreCase(letter)) {
          mRvContacts.moveToPosition(0);
        } else {
          // 找出第一个对应字母的位置后，滑动到指定位置
          for (int i = 0; i < mFriendList.size(); i++) {
            Friend friend = mFriendList.get(i);
            //String c = PinyinUtils.getPinyin(friend.getFriendUserInfo().getUsername()).charAt(0) + "";
            String c =  friend.getPinyin().charAt(0) + "";
            if (c.equalsIgnoreCase(letter)) {
              mRvContacts.moveToPosition(i);
              break;
            }
          }
        }
      }
    });
    // 新朋友
    mLlNewFriend.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        Toast.makeText(mContext, "新朋友", Toast.LENGTH_SHORT).show();
        if (mVNewFriendUnread.getVisibility() == View.VISIBLE) {
          mVNewFriendUnread.setVisibility(View.GONE);
        }
        startActivityFragment(NewFriendActivity.class, null);
        //getActivity().startActivityForResult(new Intent(getActivity(), NewFriendActivity.class), MainActivity.REQ_CLEAR_UNREAD);
      }
    });
    // 群聊
    mLlGroupCheat.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //getActivity().startActivityFragment(new Intent(getActivity(), TeamCheatListActivity.class));
        Toast.makeText(mContext, "群聊", Toast.LENGTH_SHORT).show();
      }
    });
    // 标签
    mLlTag.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //getActivity().startActivityFragment(new Intent(getActivity(), AllTagActvitiy.class));
        Toast.makeText(mContext, "标签", Toast.LENGTH_SHORT).show();
      }
    });
    // 公众号
    mLlOfficial.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        Toast.makeText(mContext, "公众号", Toast.LENGTH_SHORT).show();
      }
    });
  }

  /**
   * 显示所触摸到的字母
   *
   * @param letter 字母
   */
  private void showLetter(String letter) {
    mTvLetter.setVisibility(View.VISIBLE);
    mTvLetter.setText(letter);
    new Handler().postDelayed(new Runnable() {
      @Override public void run() {
        mTvLetter.setVisibility(View.GONE);
      }
    }, 500);
  }

  @Override protected void initData() {
    initHeaderViewAndFooterView();
    setAdapter();
    updateFriendList();
  }

  /**
   * 设置适配器
   */
  private void setAdapter() {
    mAdapter =
        new LQRAdapterForRecyclerView<Friend>(mContext, R.layout.item_contact_cv, mFriendList) {
          @Override
          public void convert(LQRViewHolderForRecyclerView helper, Friend item, int position) {
            final UserInfo info = item.getFriendUserInfo();
            // 设置头像
            ImageLoaderFactory.getLoader()
                .loadAvatar((ImageView) helper.getView(R.id.ivHeader_contact_cv),
                    (info.getAvatar() != null ? info.getAvatar() : null), R.mipmap.header);

            if (null != mFriendList) {
              String str = "";
              //得到当前字母
              //String currentLetter = PinyinUtils.getPinyin(info.getUsername()).charAt(0) + "";
              String currentLetter = item.getPinyin().charAt(0) + "";

              if (position == 0) {
                str = currentLetter;
              } else {
                //得到上一个字母
                //String preLetter = PinyinUtils.getPinyin(mFriendList.get(position - 1).getFriendUserInfo().getUsername()).charAt(0) + "";
                String preLetter = mFriendList.get(position - 1).getPinyin().charAt(0) + "";
                //如果和上一个字母的首字母不同则显示字母栏
                if (!preLetter.equalsIgnoreCase(currentLetter)) {
                  str = currentLetter;
                }

                int nextIndex = position + 1;
                if (nextIndex < mFriendList.size() - 1) {
                  //得到下一个字母
                  //String nextLetter = PinyinUtils.getPinyin(mFriendList.get(nextIndex).getFriendUserInfo().getUsername()).charAt(0) + "";
                  String nextLetter = mFriendList.get(nextIndex).getPinyin().charAt(0) + "";
                  //如果和下一个字母的首字母不同则隐藏下划线
                  if (!nextLetter.equalsIgnoreCase(currentLetter)) {
                    helper.setViewVisibility(R.id.vLine_contact_cv, View.INVISIBLE);
                  } else {
                    helper.setViewVisibility(R.id.vLine_contact_cv, View.VISIBLE);
                  }
                } else {
                  helper.setViewVisibility(R.id.vLine_contact_cv, View.INVISIBLE);
                }
              }
              if (position == mFriendList.size() - 1) {
                helper.setViewVisibility(R.id.vLine_contact_cv, View.GONE);
              }

              //根据str是否为空决定字母栏是否显示
              if (TextUtils.isEmpty(str)) {
                helper.setViewVisibility(R.id.tvIndex_contact_cv, View.GONE);
              } else {
                helper.setViewVisibility(R.id.tvIndex_contact_cv, View.VISIBLE);
                helper.setText(R.id.tvIndex_contact_cv, currentLetter);
              }
            }
            // 设置昵称
            helper.setText(R.id.tvName_contact_cv, info.getUsername());

            // 好友条目点击
            helper.getView(R.id.root_contact_cv).setOnClickListener(new View.OnClickListener() {
              @Override public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt(OtherUserInfoActivity.RELATIONSHIP, OtherUserInfoActivity.FRIEND);
                bundle.putSerializable(OtherUserInfoActivity.USERINFO, info);
                startActivityFragment(OtherUserInfoActivity.class, bundle);
              }
            });
          }
        };
    mAdapter.addHeaderView(mHeaderView);
    mAdapter.addFooterView(mFooterView);

    mRvContacts.setAdapter(mAdapter.getHeaderAndFooterAdapter());
  }

  /**
   * 获得朋友列表
   */
  private void getFriendList() {
    UserManager.getInstance().queryFriends(new FindListener<Friend>() {
      @Override public void done(List<Friend> list, BmobException e) {
        if (null == e) {
          List<Friend> friends = new ArrayList<>();
          friends.clear();
          //添加首字母
          for (int i = list.size()-1; i >= 0; i--) {
            Friend friend = list.get(i);
            String username = friend.getFriendUserInfo().getUsername();
            if (username != null) {
              String pinyin = Pinyin.toPinyin(username.charAt(0));
              friend.setPinyin(pinyin.substring(0, 1).toUpperCase());
              friends.add(friend);
            }
          }
          mAdapter.setData(friends);
        } else {
          Toast.makeText(mContext, "查询好友列表失败", Toast.LENGTH_SHORT).show();
        }
      }
    });
  }

  /**
   * 更新朋友信息列表
   */
  public void updateFriendList() {
    getFriendList();
  }

  @Override protected void onContact() {
    super.onContact();
    mVNewFriendUnread.setVisibility(View.VISIBLE);
  }

  @Override protected int getFragmentLayoutId() {
    return R.layout.fragment_contacts;
  }
}
